import Vue from 'vue'
import NoImage from '@/assets/images/no-img.svg'
import moneySymbol from '@/const/CurrencySymbol'
// import Store from '@/store/index'
import dayjs from 'dayjs'
import QuarterOfYear from 'dayjs/plugin/quarterOfYear'
dayjs.extend(QuarterOfYear)
export const formatData = (num, types) => {
  if (isNaN(num)) {
    return ''
  } else {
    if (types) {
      var type = types.toLowerCase()
      if (type === 'spend') {
        return formatSpendsMoney(num)
      } else if (type.includes('budget')) {
        return formatBudgetMoney(num)
      } else if (type.includes('sales')) {
        return formatSalesMoney(num)
      } else if (
        type === 'ctr' ||
        type === 'cvr' ||
        type === 'buyboxpct' ||
        type === 'buyboxpctlastweek' ||
        type === 'availabilitypct' ||
        type === 'availabilitypctlastweek' ||
        type.includes('acos') ||
        type.includes('placement') ||
        type.includes('platform') ||
        type === 'shareofshelf' ||
        type === 'organicsov' ||
        type === 'paidsov' ||
        type === 'sppaidsov' ||
        type === 'sbpaidsov' ||
        type === 'adsfrequency' ||
        type === 'topthreerate' ||
        type === 'pageonerate'
      ) {
        return formatPercent100(num)
      } else if (
        type === 'conversion' ||
        type.includes('impression') ||
        type === 'click' ||
        type === 'clicks' ||
        type === 'inventorycount' ||
        type === 'pageviews' ||
        type === 'pageviewlastweek' ||
        type.includes('saleunits') ||
        type === 'totalorders' ||
        type === 'reviewscount' ||
        type === 'averagerating' ||
        type === 'avgorganicposition' ||
        type === 'avgpaidposition' ||
        type === 'avgposition' ||
        type === 'stars' ||
        type === 'reviews'
      ) {
        return toThousandsx(num)
      } else {
        return formatMoney(num)
      }
    } else {
      return formatMoney(num)
    }
  }
}
export const toThousands = (a = 0) => {
  if (a === null) {
    return '--'
  }
  var abs = ''
  var xiaoshu = '' // 用来记录参数小数数值包括小数点
  var zhengshu = '' // 用来记录参数录整数数值
  if (a < 0) {
    a = Math.abs(a)
    abs = '-'
  }
  if (a < 1000) {
    // 当参数小于1000的时候直接返回参数
    return abs + a
  } else {
    var t = String(a) // 将整数转换成字符串
    if (t.indexOf('.') > 0) {
      // 如果参数存在小数，则记录小数部分与整数部分
      var index = t.indexOf('.')
      xiaoshu = t.slice(index, t.length)
      zhengshu = t.slice(0, index)
    } else {
      // 否则整数部分的值就等于参数的字符类型
      zhengshu = t
    }
    var num = parseInt(zhengshu.length / 3) // 判断需要插入千位分割符的个数

    // 将整数1234567890部分拆分为2部分，变量head:1   变量body:123456789
    var head = zhengshu.slice(0, zhengshu.length - num * 3)
    if (head.length > 0) {
      // 如果head存在，则在head后面加个千位分隔符，
      head += ','
    }
    var body = zhengshu.slice(zhengshu.length - num * 3, zhengshu.length)

    // 将body字符串123456789转换成一个字符数组arr2 = ['123','456','789']
    var arr2 = []
    for (var i = 0; i < num; i++) {
      arr2.push(body.slice(i * 3, i * 3 + 3))
    }
    body = arr2.join(',') // 将数组arr2通过join(',')   方法，拼接成一个以逗号为间隔的字符串

    zhengshu = head + body // 拼接整数部分
    var result = zhengshu + xiaoshu // 最后拼接整数和小数部分
    return abs + result // 返回结果
  }
}
export const formatBudgetMoney = (t) => {
  if (isNaN(t)) {
    return '$0'
  }
  var num = Number(t)
  if (num > 1 || num > -1) {
    num = parseInt(num)
  } else {
    num = num.toFixed(2)
  }
  num = num.toString().split('.') // 分隔小数点
  var arr = num[0].split('').reverse() // 转换成字符数组并且倒序排列
  var res = []
  for (var i = 0, len = arr.length; i < len; i++) {
    if (i % 3 === 0 && i !== 0) {
      res.push(',') // 添加分隔符
    }
    res.push(arr[i])
  }
  res.reverse() // 再次倒序成为正确的顺序
  if (num[1]) {
    // 如果有小数的话添加小数部分
    res = res.join('').concat('.' + num[1])
  } else {
    res = res.join('')
  }
  return '$' + res
}
export const formatThousands = (t) => {
  t = Number(t)
  return toThousands(t.toFixed(0))
}
export const toThousandsx = (t, state = false) => {
  if (t === null) {
    return '--'
  }
  if (state) {
    return toThousands(t)
  }
  t = Number(t)
  if (t < 0) {
    t = Math.abs(t)
    if (t > 1000000) {
      return '-' + toThousands((t / 1000000).toFixed(1)) + 'M'
    } else if (t > 10000) {
      return '-' + toThousands((t / 1000).toFixed(1)) + 'K'
    } else {
      return '-' + toThousands(t.toFixed(0))
    }
  } else {
    if (t > 1000000) {
      return toThousands((t / 1000000).toFixed(1)) + 'M'
    } else if (t > 10000) {
      return toThousands((t / 1000).toFixed(1)) + 'K'
    } else {
      return toThousands(t.toFixed(0))
    }
  }
}
export const pacvuePercentWithThousandsx = (t) => {
  if (t === null) {
    return '--'
  }
  t = Number(t)
  t = Math.abs(t)
  if (t > 1000000) {
    return toThousands((t / 1000000).toFixed(1)) + 'M' + '%'
  } else if (t > 10000) {
    return toThousands((t / 1000).toFixed(1)) + 'K' + '%'
  } else {
    return t + '%'
  }
}
export const formatMoney = (money = 0, num = '$') => {
  var type = num

  if (num && num === '￥') {
    return type + toThousands(Math.round(Number(money)))
  }
  money = Number(money)
  const absMoney = Math.abs(money)
  if (absMoney > 1000000) {
    return type + toThousands((money / 1000000).toFixed(2)) + 'M'
  } else if (absMoney > 10000) {
    return type + toThousands(Number(money / 1000).toFixed(2)) + 'K'
  } else {
    return type + toThousands(Number(money).toFixed(2))
  }
}
export const formatMoney1 = (money, type = '$') => {
  if (type && type === '￥') {
    return type + toThousands(Math.round(Number(money)))
  }
  return type + toThousands(Number(money).toFixed(2))
}
export const formatSalesMoney = (
  money = 0,
  num = '$',
  state = false,
  decimal = false
) => {
  var type = num
  if (money === null) {
    return '--'
  }
  if (state) {
    if (decimal) {
      return type + toThousands(money.toFixed(2))
    }
    return type + toThousands(money.toFixed(2))
  }
  if (money === 0) {
    return type + money
  }
  if (num && num === '￥') {
    return type + toThousands(Math.round(Number(money)))
  }
  if (money < 0) {
    money = Math.abs(money)
    if (money >= 1000000) {
      return type + '-' + toThousands((money / 1000000).toFixed(2)) + 'M'
    } else if (money > 10000) {
      return type + '-' + toThousands(Number(money / 1000).toFixed(2)) + 'K'
    } else if (money > 10) {
      return type + '-' + toThousands(Number(money).toFixed(2))
    } else if (money > 0.1) {
      return type + '-' + toThousands(Number(money).toFixed(2))
    } else {
      return type + '-' + toThousands(Number(money).toFixed(2))
    }
  } else {
    if (money >= 1000000) {
      return type + toThousands((money / 1000000).toFixed(2)) + 'M'
    } else if (money > 10000) {
      return type + toThousands(Number(money / 1000).toFixed(2)) + 'K'
    } else if (money > 10) {
      return type + toThousands(Number(money).toFixed(2))
    } else if (money > 0.1) {
      return type + toThousands(Number(money).toFixed(2))
    } else {
      return type + toThousands(Number(money).toFixed(2))
    }
  }
}
// export const formatSalesMoneyWithOutabs(money = 0, num = '$') {
//   var type = num
//   if (money === 0) {
//     return type + money
//   }
//   if (money === null) {
//     return '--'
//   }
//   if (num && num === '￥') {
//     return type + toThousands(Math.round(Number(money)))
//   }
//   if (money < 0) {
//     money = Math.abs(money)
//     if (money >= 1000000) {
//       return type + '-' + toThousands((money / 1000000).toFixed(1)) + 'M'
//     } else if (money > 10000) {
//       return type + '-' + toThousands(Number(money / 1000).toFixed(1)) + 'K'
//     } else if (money > 10) {
//       return type + '-' + toThousands(Number(money).toFixed(0))
//     } else if (money > 0.1) {
//       return type + '-' + toThousands(Number(money).toFixed(1))
//     } else {
//       return type + '-' + toThousands(Number(money).toFixed(2))
//     }
//   } else {
//     if (money >= 1000000) {
//       return type + toThousands((money / 1000000).toFixed(1)) + 'M'
//     } else if (money > 10000) {
//       return type + toThousands(Number(money / 1000).toFixed(1)) + 'K'
//     } else if (money > 10) {
//       return type + toThousands(Number(money).toFixed(0))
//     } else if (money > 0.1) {
//       return type + toThousands(Number(money).toFixed(1))
//     } else {
//       return type + toThousands(Number(money).toFixed(2))
//     }
//   }
// }
export const formatSpendsMoney = (money = 0, num = '$') => {
  var type = num

  if (num && num === '￥') {
    return type + toThousands(Math.round(Number(money)))
  }
  if (money >= 1000000) {
    return type + toThousands((money / 1000000).toFixed(1)) + 'M'
  } else if (money > 10000) {
    return type + toThousands(Number(money / 1000).toFixed(1)) + 'K'
  } else if (money > 1) {
    return type + toThousands(Number(money).toFixed(0))
  } else {
    return type + toThousands(Number(money).toFixed(2))
  }
}
export const formatMoneyInt = (money, num = '$') => {
  var type = num
  return type + toThousands(Number(money).toFixed(0))
}
export const formatPercent = (v) => {
  if (v === null) {
    return '--'
  } else if (v === 0) {
    return '0.00%'
  }
  v = Number(v)
  return v.toFixed(2) + '%'
}
export const formatPercent1 = (v) => {
  if (v === null) {
    return '--'
  } else if (v === 0) {
    return '0.0%'
  }
  v = Number(v)
  return v.toFixed(1) + '%'
}
export const formatPercentint = (v) => {
  if (v === null) {
    return '--'
  } else if (v === 0) {
    return '0%'
  }
  v = Number(v)
  return v.toFixed(0) + '%'
}
export const formatPercentOther100 = (v) => {
  if (v === null) {
    return '--'
  } else if (v === 0) {
    return '0%'
  }
  v = Number(v)
  if (v === 100) {
    return v.toFixed(0) + '%'
  } else {
    return v.toFixed(1) + '%'
  }
}
export const formatPercent100 = (v = 0) => {
  if (v === null) {
    return '--'
  } else if (v === 0) {
    return '0.0%'
  }
  v = Number(v)
  if (v >= 100) {
    return v.toFixed(0) + '%'
  } else {
    return v.toFixed(2) + '%'
  }
}
export const pickData = (data, field) => {
  return data.map(function(item) {
    var result = {}
    for (var key in item) {
      if (
        Object.prototype.hasOwnProperty.call(item, key) &&
        field.includes(key)
      ) {
        result[key] = item[key]
      }
    }
    return result
  })
}
export const dataISminus = (val) => {
  if (val <= 0) {
    return true
  } else {
    return false
  }
}
export const colorclass = (j, val) => {
  const arr = [
    'ctr',
    'cvr',
    'click',
    'clicks',
    'spc',
    'sales',
    'relatedclicksales',
    'brandviewsales',
    'viewsales',
    'roas',
    'clickSales',
    'clicksales',
    'clickROAS',
    'clickroas',
    'brandClickSales',
    'brandClickROAS',
    'brandclicksales',
    'brandclickroas',
    'troas',
    'revenue',
    'saleunits',
    'orders',
    'organicrevenue',
    'totalorders',
    'shareOfShelf',
    'shareofshelf',
    'organicSOV',
    'organicsov',
    'spPaidSOV',
    'sppaidsov',
    'adsFrequency',
    'adsfrequency',
    'avgPosition',
    'avgposition',
    'avgOrganicPosition',
    'avgorganicposition',
    'avgPaidPosition',
    'avgpaidposition',
    'topThreeRate',
    'topthreerate',
    'pageOneRate',
    'pageonerate',
    'sbPaidSOV',
    'sbpaidsov',
    'paidSOV',
    'paidsov'
  ]
  const arr1 = [
    'acos',
    'cpa',
    'cpc',
    'cpm',
    'clickACOS',
    'clickacos',
    'brandClickACOS',
    'brandclickacos',
    'tacos'
  ]
  if (arr.includes(j)) {
    return dataISminus(val) ? 'red' : 'green'
  } else if (arr1.includes(j)) {
    return dataISminus(val) ? 'green' : 'red'
  } else {
    return 'gray'
  }
}
export const colorclass1 = (j, val) => {
  j = (j || '').toLowerCase()
  if (
    [
      'ctr',
      'cvr',
      'click',
      'clicks',
      'spc',
      'sales',
      'relatedclicksales',
      'brandviewsales',
      'viewsales',
      'roas',
      'clickSales',
      'clicksales',
      'clickROAS',
      'clickroas',
      'brandClickSales',
      'brandClickROAS',
      'brandclicksales',
      'brandclickroas',
      'troas',
      'revenue',
      'saleunits',
      'orders',
      'organicrevenue',
      'totalorders',
      'shareOfShelf',
      'shareofshelf',
      'organicSOV',
      'organicsov',
      'spPaidSOV',
      'sppaidsov',
      'adsFrequency',
      'adsfrequency',
      'avgPosition',
      'avgposition',
      'avgOrganicPosition',
      'avgorganicposition',
      'avgPaidPosition',
      'avgpaidposition',
      'topThreeRate',
      'topthreerate',
      'pageOneRate',
      'pageonerate',
      'sbPaidSOV',
      'sbpaidsov',
      'paidSOV',
      'paidsov'
    ].includes(j)
  ) {
    return val === 0 ? '#999999' : val < 0 ? redType(val) : '#5CBF8E'
  } else if (
    [
      'acos',
      'cpa',
      'cpc',
      'cpm',
      'clickACOS',
      'clickacos',
      'brandClickACOS',
      'brandclickacos',
      'tacos'
    ].includes(j)
  ) {
    return val === 0 ? '#999999' : val < 0 ? '#5CBF8E' : redType(val)
  } else {
    return '#999999'
  }
}
export const redType = (val) => {
  const newVal = val > 0 ? val : 0 - val
  if (newVal <= 10) {
    return '#5CBF8E'
  } else if (newVal <= 50) {
    return '#FBAF46'
  } else {
    return '#EE8873'
  }
}

export const equalArr = (a, b) => {
  // 增加判断，数组定义后为空是null清空的数组相等判断
  if (
    (a === null && b && b.length === 0) ||
    (a && a.length === 0 && b === null)
  ) {
    return false
  }
  if (!b || !a) {
    return true
  }
  // compare lengths - can save a lot of time
  if (a.length !== b.length) {
    return true
  }

  for (var i = 0; i < a.length; i++) {
    // Check if we have nested arrays
    if (a[i] instanceof Array && b[i] instanceof Array) {
      // recurse into the nested arrays
      if (equalArr(a[i], b[i])) return true
    } else if (a[i] !== b[i]) {
      // Warning - two different object instances will never be equal: {x:20} != {x:20}
      return true
    }
  }
  return false
}
export const getSelectName = (type, name, arr) => {
  var obj = {}
  var showName = ''
  var idsarr = []
  var textarr = []
  var arrTitle = []
  var arrTitle1 = []

  for (var i of arr) {
    idsarr.push(i[type])
    textarr.push(i[name])
  }

  var num = 0
  textarr.map(function(val) {
    const title = val
    num++
    arrTitle.push(num + '.' + title + '<br>')
  })
  if (arrTitle.length > 5) {
    arrTitle1 = arrTitle.slice(0, 5)
    showName = arrTitle1.join(' ') + '6. ...'
  } else {
    showName = arrTitle.join(' ')
  }
  obj.showName = showName
  obj.idsarr = idsarr
  obj.textarr = textarr
  return obj
}
export const copyJSON = (str) => {
  var a = JSON.stringify(str)
  var b = JSON.parse(a)
  return b
}
export const handleFixed = (v, num = 1) => {
  v === Number(v)
  return v.toFixed(num)
}
export const exchangeRate = (v, num = 1) => {
  v === Number(v)
  if (v === 1) {
    return 1
  }
  return v.toFixed(num)
}
export const parseTime = (time, cFormat) => {
  if (!time && !cFormat) {
    return null
  }
  if (!time) {
    return '-'
  }
  const format = cFormat || '{m}/{d}/{y} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([mdyhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}
export const inputDetection = (n, o) => {
  if (isNaN(n)) {
    return o
  }
  if (o === '0' || o === '0.') {
    if (Number(n) >= 1) {
      return '0.' + Number(n)
    }
    return n
  }
  if (Number(n) > 99999999) {
    return o
  }
  var str = n.toString()
  var num = str.split('.')
  if (num[1] && num[1].length > 2) {
    return Number(n).toFixed(2)
  }
  if (num[0].length > 1 && num[0].indexOf('0') === 0) {
    return Number(n)
  }
  return n
}
export const inputInt = (n, o) => {
  if (Number(n) > 900) {
    return 900
  }
  if (Number(n) < 0) {
    return 0
  }
  return inputDetection(n, o)
}
export const formatSourceData = (data, obj) => {
  if (!obj) {
    return null
  }
  let dataJson = JSON.stringify(data)
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, 'key')) {
      const element = obj[key]
      dataJson = dataJson.replace(new RegExp(`"${key}"`, 'gm'), `"${element}"`)
    }
  }
  return JSON.parse(dataJson)
}
export const formatTreeSelectData = (res) => {
  var ary = []
  for (var i of res) {
    var checked = []
    var sublist = []
    for (var j of i.subTags) {
      var sub = {
        label: j.tagName,
        searchlabel: j.tagName.toLowerCase(),
        disabled: j.isSelected,
        searchShow: true,
        value: j.tagId
      }
      sublist.push(sub)
      if (j.isSelected) {
        checked.push(j.tagId)
      }
    }
    var parent = {
      label: i.tagName,
      searchlabel: i.tagName.toLowerCase(),
      value: i.tagId,
      subTagCount: i.subTagCount,
      sublist: sublist,
      checkAll: !!(
        (checked.length === i.subTagCount && i.subTagCount !== 0) ||
        i.isSelected
      ),
      isIndeterminate: false,
      isShow: false,
      searchShow: true,
      checkgroup: [],
      disabled: !!(
        (checked.length === i.subTagCount && i.subTagCount !== 0) ||
        i.isSelected
      )
    }
    ary.push(parent)
  }
  return copyJSON(ary)
}
export const buLing = (n) => {
  var number = Number(n)
  if (number < 10) {
    number = '0' + number
  }
  return number.toString()
}
export const isNull = (str) => {
  if (str === '') return true
  var regu = '^[ ]+$'
  var re = new RegExp(regu)
  return re.test(str)
}
export const filterData = (arr, key) => {
  const result = []
  const obj = {}
  for (var i = 0; i < arr.length; i++) {
    if (!obj[arr[i][key]]) {
      result.push(arr[i])
      obj[arr[i][key]] = true
    }
  }
  return result
}
export const uniq = (array) => {
  return Array.from(new Set(array))
  // var temp = [] // 一个新的临时数组
  // for (var i = 0; i < array.length; i++) {
  //   if (i === 0) {
  //     temp.push(array[i])
  //   } else {
  //     if (temp.includes(array[i])) {
  //       temp.push(array[i])
  //     }
  //   }
  // }
  // return temp
}
export const uniqTextarea = (textarea) => {
  var a = textarea.split('\n')
  var b = []
  for (var i of a) {
    if (i.trim() !== '') {
      b.push(i.trim())
    }
  }
  return uniq(b)
}

export const getWeekOfYear = (today) => {
  var firstDay = new Date(today.getFullYear(), 0, 1) // 获取今年第一天
  var d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000)
  var result = Math.ceil((d + (firstDay.getDay() + 1 - 1)) / 7)
  if (result < 10) {
    result = '0' + result
  }
  return result
}
export const DownLoad = (res) => {
  if (res.data.type.includes('json')) {
    var reader = new FileReader()
    reader.readAsText(res.data)
    reader.onload = (e) => {
      var err = JSON.parse(e.target.result)
      Vue.prototype.$alert('<p style="font-size:12px">' + err.msg + '</p>', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: 'OK',
        type: 'warning'
      })
    }
    return false
  }
  var blob = new Blob([res.data])
  var downloadElement = document.createElement('a')
  var href = window.URL.createObjectURL(blob) // 创建下载的链接
  downloadElement.href = href
  var arr = res.headers['content-disposition'].split(';')
  downloadElement.download = arr[1].slice(10) // 下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
  return true
}
export const BulkDownLoad = (res) => {
  if (res?.data?.type?.includes('json')) {
    var reader = new FileReader()
    reader.readAsText(res.data)
    reader.onload = (e) => {
      var err = JSON.parse(e.target.result)
      Vue.prototype.$alert('<p style="font-size:12px">' + err.msg + '</p>', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: 'OK',
        type: 'warning'
      })
    }
    return false
  }
  var blob = new Blob([res.data])
  var downloadElement = document.createElement('a')
  var href = window.URL.createObjectURL(blob)
  downloadElement.href = href
  var arr = res.headers['content-disposition'].split(';')
  const headStr = arr[1].slice(10)
  const str = headStr.startsWith('"') ? headStr.replace(/\"/g, '') : headStr
  downloadElement.download = str
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement)
  window.URL.revokeObjectURL(href)
  return true
}
export const formatPercentToe = (value) => {
  let str = ''
  if (value > 0) {
    const p = Math.floor(Math.log(value) / Math.LN10)
    const val = (value / 10 ** p).toFixed(1)
    str = val + 'e' + p + '%'
  } else {
    value = Number(value.toString().substring(1, value.length))
    const p = Math.floor(Math.log(value) / Math.LN10)
    const val = (value / 10 ** p).toFixed(1)
    str = '-' + val + 'e' + p + '%'
  }
  return str
}
export const tagCampaign = (tag) => {
  if (tag) {
    const list = []
    tag.forEach((item) => {
      if (item !== 'NoTagCampaign') {
        list.push(item)
      }
    })
    return list
  } else {
    return []
  }
}
export const noTagCampaign = (tag) => {
  if (tag) {
    let b = false
    tag.forEach((item) => {
      if (item === 'NoTagCampaign') {
        b = true
      }
    })
    return b
  } else {
    return false
  }
}
export const formatColumns = (list, showCompareCheck) => {
  var ary = []
  var index = 0
  for (var i of copyJSON(list)) {
    if (i.isChecked && i.prop) {
      if (i.type === 'subtag' && index === 0) {
        ary.push('tagColumns')
        index++
      }
      ary.push(i.prop)
      if (i.prevProp && showCompareCheck) {
        ary.push(i.prop + 'Compare')
        ary.push(i.prevProp)
      }
    }
  }
  return ary
}
export const marketCodeBudget = (val) => {
  // 返回根据表channel切换不同的货币单位
  var city = ''
  if (val.indexOf(' ') < 0) {
    city = val
  } else {
    city = val.split(/[ ]+/)[1]
  }

  return moneySymbol[city]
}
export const marketAddress = (val, asin) => {
  // 页面channel跳转拼接路径
  var city = ''
  var http = 'https://www.amazon.'
  var asinStr = '/dp/' + asin
  if (val.indexOf(' ') < 0) {
    city = val
  } else {
    city = val.split(/[ ]+/)[1]
  }
  switch (city) {
    case 'AU':
      return http + 'com.au' + asinStr
    case 'BR':
      return http + 'com.br' + asinStr
    case 'CA':
      return http + 'ca' + asinStr
    case 'CN':
      return http + 'cn' + asinStr
    case 'FR':
      return http + 'fr' + asinStr
    case 'DE':
      return http + 'de' + asinStr
    case 'IN':
      return http + 'in' + asinStr
    case 'IT':
      return http + 'it' + asinStr
    case 'JP':
      return http + 'co.jp' + asinStr
    case 'MX':
      return http + 'com.mx' + asinStr
    case 'NL':
      return http + 'nl' + asinStr
    case 'ES':
      return http + 'es' + asinStr
    case 'TR':
      return http + 'com.tr' + asinStr
    case 'UK':
      return http + 'co.uk' + asinStr
    case 'US':
      return http + 'com' + asinStr
    case 'AE':
      return http + 'ae' + asinStr
    case 'SA':
      return http + 'sa' + asinStr
    case 'PL':
      return http + 'pl' + asinStr
    case 'EG':
      return http + 'eg' + asinStr
    case 'SG':
      return http + 'sg' + asinStr
    case 'BE':
      return http + 'com.be' + asinStr
    default:
      return http + 'com' + asinStr
  }
}
export const replaceOldImage = (data) => {
  if (data === null || data === 'null' || data === '' || !data) {
    return NoImage
  }
  var src = data.replace(
    'http://ecx.images-amazon.com',
    'https://m.media-amazon.com'
  )
  return src
}
export const getNumberResult = (val) => {
  if (val === null || val === 0) {
    return '0.00%'
  } else if (val < 0) {
    return Math.abs(val).toFixed(2) + '%'
  } else {
    return val.toFixed(2) + '%'
  }
}
/**
 *
 * @param {Number} val 数值
 * @param {Number} type 类型
 * 获取chart数值条颜色
 * 1、中性值上升或下降都使用灰色。
 * 2、下降是良性的值，下降全部用绿色。上升0-50%之间用黄色，51%以上用红色。
 * 3、上升为良性的值，上升全部用绿色。下降0-50%之间用黄色，51%以上用红色。
 */
export const getColor = (val, type = 3) => {
  // 中性值
  if (type === 1) {
    return 'tendency zone'
  }
  // 下降是良性
  if (type === 2) {
    if (!val) {
      return 'tendency zone'
    } else if (val < 0) {
      return 'tendency greenNum'
    } else if (val <= 50) {
      return 'tendency yellow'
    } else {
      return 'tendency redNum'
    }
  }
  // 上升为良性
  if (type === 3) {
    if (!val) {
      return 'tendency zone'
    } else if (val > 0) {
      return 'tendency greenNum'
    } else if (val >= -50) {
      return 'tendency yellow'
    } else {
      return 'tendency redNum'
    }
  }
}
export const getTextColor = (val) => {
  if (!val) {
    return ''
  }
  if (val === -1) {
    return '#999'
  }
  if (val >= 0 && val < 6) {
    return '#FF6C5C'
  } else if (val >= 6 && val < 8) {
    return '#FFB03E'
  } else if (val >= 8) {
    return '#52C41B'
  }
}
export const getTextColorByType = (val) => {
  if (!val) {
    return ''
  }
  if (val === 1) {
    return '#FF6C5C'
  }
  if (val === 2) {
    return '#FFB03E'
  }
  if (val === 3) {
    return '#52C41B'
  }
}
// export const getIconClass(val) {
//   if (val === null) {
//     return 'svg-tendency zoneWord'
//   } else if (val >= -10) {
//     return 'svg-tendency greenWord'
//   } else if (val < -10 & val >= 50) {
//     return 'svg-tendency yellowWord'
//   } else {
//     return 'svg-tendency redWord'
//   }
// }
/**
 * 获取上升下降箭头图标
 * @param {Number} val 数值
 * @param {Number} type 类型
 * 1、中性值上升或下降都使用iconzhiwubianhua
 * 2、下降是良性值，下降使用iconshujushangsheng，上升使用iconshujuxiajiang
 * 3、上升为良性值，上升使用iconshujushangsheng，下降使用iconshujuxiajiang
 * @returns {string} 字体图标类名
 */
export const getIcon = (val, type = 3) => {
  if (val === null || val === 0) {
    return 'iconzhiwubianhua'
  }
  if (val > 0) {
    return type === 3 ? 'iconshujushangsheng' : type === 2 ? 'iconshujuxiajiang' : 'iconzhiwubianhua'
  } else {
    return type === 3 ? 'iconshujuxiajiang' : type === 2 ? 'iconshujushangsheng' : 'iconzhiwubianhua'
  }
}
export const pacvueNullForZore = (v) => {
  if (v === null) {
    return 0
  } else {
    return v
  }
}
export const pacvuePercent = (v) => {
  if (v === null) {
    return '--'
  } else {
    return Math.abs(v) + '%'
  }
}
export const pacvuePercentWithoutabs = (v) => {
  if (!v) {
    return '--'
  } else {
    return v + '%'
  }
}
export const pacvuePercentForChart = (v) => {
  // 判断是否有多位小数
  var status = v.toString().split('.')[1] > 9
  if (v === null) {
    return '--'
  }
  if (status) {
    return v.toFixed(1) + '%'
  } else {
    return v + '%'
  }
}

const magic = [
  10, 15, 20, 25, 30, 40, 50, 60, 70, 80, 90, 100, 125, 150, 200, 250, 300, 350,
  400, 500
]
export const zeroPadding = (num) => {
  if (num <= 2) {
    return 10
  } else {
    return Math.pow(10, num - 1)
  }
}
export const getMaxInt = (num) => {
  const int = zeroPadding((num + '').length)
  return Math.ceil(num / int) * int
}

export const getChartMaxMin = (dataList, selectLegend = true) => {
  if (!selectLegend || dataList.length === 0) {
    return {}
  }
  let splitNumber = 4
  const scale = 1000
  let max = Math.max(...dataList) * scale
  const min = Math.min(...dataList) > 0 ? 0 : Math.min(...dataList) * scale
  if (max - min < 4000) {
    max = Math.ceil((max - min) / 4000) * 4000
  }
  if (min * max < 0) {
    splitNumber = splitNumber - 1
  }
  const tempGap = (max - min) / splitNumber
  const multiple = Math.pow(10, Math.floor(Math.log10(tempGap) - 1))
  const tempStep = tempGap / multiple
  var estep = 0
  for (var i = 0; i < magic.length; i++) {
    if (magic[i] > tempStep) {
      estep = magic[i] * multiple
      break
    }
  }
  let maxi, mini
  // const maxRem = parseInt(max / estep) % 2 === 0 ? parseInt(max / estep) + 2 : parseInt(max / estep) + 1
  // const minRem = parseInt(min / estep) % 2 === 0 ? parseInt(min / estep) - 1 : parseInt(min / estep) - 2
  // 这里的parseInt是我无意中写出来的，本来我是想对maxi使用Math.floor，对mini使用Math.ceil的。这样能向下取到邻近的一格，不过后面发现用parseInt好像画出来图的比较好看
  maxi = parseInt(max / estep + 1) * estep // 最终效果是当max/estep属于(-1,Infinity)区间时，向上取1格，否则取2格。
  mini = parseInt(min / estep - 1) * estep // 当min/estep属于(-Infinity,1)区间时，向下取1格，否则取2格。
  // 当min/estep属于(-Infinity,1)区间时，向下取1格，否则取2格。
  // 如果max和min刚好在刻度线的话，则按照上面的逻辑会向上或向下多取一格
  if (max === 0) maxi = 0 // 这里进行了一次矫正，优先取到0刻度
  if (min === 0) mini = 0
  if ((maxi - mini) / estep < 4) {
    if (Math.abs(maxi) > Math.abs(mini)) {
      maxi = max > 0 ? splitNumber * estep : splitNumber * estep * -1
    } else {
      mini = min > 0 ? splitNumber * estep : splitNumber * estep * -1
    }
  }
  return {
    max: maxi / scale,
    min: Math.min(...dataList) > 0 ? 0 : mini / scale,
    interval: estep / scale
  }
}
export const mergeArr = (json) => {
  const result = []
  for (const key in json) {
    json[key].forEach((value, index) => {
      if (isBlank(result[index])) {
        result[index] = 0
      }
      result[index] += value
    })
  }
  return result
}
export const isBlank = (val) => {
  if (val == null || val === '') {
    return true
  }
}
export const handleSellerPage = (val, seller) => {
  var city = ''
  var http = 'https://www.amazon.'
  var sellerStr = '/sp?seller=' + seller
  if (val.indexOf(' ') < 0) {
    city = val
  } else {
    city = val.split(/[ ]+/)[1]
  }
  switch (city) {
    case 'AU':
      return http + 'com.au' + sellerStr
    case 'BR':
      return http + 'com.br' + sellerStr
    case 'CA':
      return http + 'ca' + sellerStr
    case 'CN':
      return http + 'cn' + sellerStr
    case 'FR':
      return http + 'fr' + sellerStr
    case 'DE':
      return http + 'de' + sellerStr
    case 'IN':
      return http + 'in' + sellerStr
    case 'IT':
      return http + 'it' + sellerStr
    case 'JP':
      return http + 'co.jp' + sellerStr
    case 'MX':
      return http + 'com.mx' + sellerStr
    case 'NL':
      return http + 'nl' + sellerStr
    case 'ES':
      return http + 'es' + sellerStr
    case 'TR':
      return http + 'com.tr' + sellerStr
    case 'UK':
      return http + 'co.uk' + sellerStr
    case 'US':
      return http + 'com' + sellerStr
    case 'AE':
      return http + 'ae' + sellerStr
    case 'SA':
      return http + 'sa' + sellerStr
    default:
      return http + 'com' + sellerStr
  }
}

/**
 * @description: 严格类型判断
 * @param {any} typeObject
 * @return {String} Object Array
 */
export const toClass = (typeObject) => {
  return Object.prototype.toString
    .call(typeObject)
    .split(' ')[1]
    .replace(']', '')
}
/**
 * @description: 数字格式化
 * @param {String|Number}
 * @return {String}
 */

export const checkTime = (idx) => {
  return ('0' + idx).slice(-2)
}

/**
 * @description:
 * @param {String|Number|Date} dateParams // 日期对象  时间戳(数字 , 字符串)
 * @param {String} formatKey // 格式化文本  YYYY MM DD hh mm ss 正则匹配
 * @return {Object}
 */
export const formatDate = (dateParams, formatKey = 'YYYY-MM-DD hh:mm:ss') => {
  const dateType = toClass(dateParams)
  let dateObj
  if (dateType === 'Number' || dateType === 'String') {
    if (dateType === 'String') {
      dateParams = dateParams.replace(/\-/gm, '/')
    }
    dateObj = new Date(dateParams)
  } else if (dateType === 'Date') {
    dateObj = dateParams
  } else {
    throw TypeError('param dateParams type must be [String,Number,Date]')
  }
  const year = dateObj.getFullYear()
  const month = checkTime(dateObj.getMonth() + 1)
  const date = checkTime(dateObj.getDate())
  const hours = checkTime(dateObj.getHours())
  const minutes = checkTime(dateObj.getMinutes())
  const seconds = checkTime(dateObj.getSeconds())
  let formatVal
  // 格式化字符串
  if (formatKey && typeof formatKey === 'string') {
    formatVal = formatKey.replace(
      /(YYYY)|(MM)|(DD)|(hh)|(mm)|(ss)/gm,
      function(match, YYYY, MM, DD, hh, mm, ss) {
        if (YYYY) {
          return year
        } else if (MM) {
          return month
        } else if (DD) {
          return date
        } else if (hh) {
          return hours
        } else if (mm) {
          return minutes
        } else if (ss) {
          return seconds
        }
      }
    )
  } else {
    throw Error('param formatKey is required or type must be String')
  }
  return {
    year,
    month,
    date,
    hours,
    minutes,
    seconds,
    formatVal,
    timestamp: dateObj.getTime()
  }
}

export const getCountry = () => {
  const req = require.context('@/assets/images/country', false, /\.png$/)
  const countryObj = {}
  req
    .keys()
    .reverse()
    .forEach((key) => {
      const pngKey = key.split('/')[1].split('.')[0]
      countryObj[pngKey] = req(key)
    })
  return countryObj
}

// 获取当前时区
export const getUniqueTimeZone = () => {
  return -(new Date().getTimezoneOffset() / 60)
}

/*
// 序列化百分比  根据小数位数进行序列化
  carryNumber // Number 小数位数进位
  fixNumber // Number 小数点位数保留位数
  @return // String 格式化字符
*/
export function formatPercentOfCarry(value, carryNumber = 2, fixNumber = 2) {
  if (value === null || value === undefined) {
    return '--'
  } else if (value === 0) {
    return '0.00%'
  }
  value = Number(value)
  return (value * (10 ** carryNumber)).toFixed(fixNumber) + '%'
}

/**
 * 数字四舍五入
 * @param num
 * @param fractionDigits 保留小数位数
 * @returns {string}
 */
export const getFixedNumber = (num, fractionDigits = 2) => {
  num = parseFloat(num)
  return (Math.round((num + Number.EPSILON) * Math.pow(10, fractionDigits)) / Math.pow(10, fractionDigits)).toFixed(fractionDigits)
}

/**
 * 金额格式化，四舍五入
 * @param money
 * @param symbol
 * @param isFullNumber
 * @returns {string}
 */
export const formatMoneyRound = (money = 0, symbol = '$', isFullNumber = false) => {
  if (symbol && symbol === '￥') {
    return symbol + toThousands(Math.round(Number(money)))
  }
  const _money = Number(money)
  if (isFullNumber) {
    return symbol + toThousands(getFixedNumber(_money))
  }
  const absMoney = Math.abs(_money)
  if (absMoney > 1000000) {
    return symbol + toThousands(getFixedNumber(_money / 1000000)) + 'M'
  } else if (absMoney > 10000) {
    return symbol + toThousands(getFixedNumber(_money / 1000)) + 'K'
  } else {
    return symbol + toThousands(getFixedNumber(_money))
  }
}

/*
// 根据转换类型获取转换后的值 - [字符串，数值，金钱，百分比]
// 金钱格式化下  默认符号为状态管理默认值
 colValue // any 格式化value
 colType // String  格式化类型 [string , number , percent , money]
 countrySymbol // String 国家符号 用于 money 格式化
 formatConfig // Object 格式化配置 -> {
    carryNumber // Number 0  percent 格式化 小数位数进位
    fixNumber // Number  2  percent 格式化 小数点位数保留位数
    moneySymbol // String  money 格式化 金钱符号 优先级大于 countrySymbol
    isFullNumber // Boolean 是否展示 [ money,number ] 全部的格式化的字符
 }
 @return // string 格式化字符串
*/
export function getColFormatValue(colValue, colType, countrySymbol, formatConfig) {
  const formatConfigAss = Object.assign({
    carryNumber: 0,
    fixNumber: 2,
    // 指定货币符号
    moneySymbol: undefined,
    isFullNumber: false
  }, formatConfig)
  if (colValue === '' || colValue === null || colValue === undefined) {
    return '--'
  }
  if (colType === 'number') {
    return toThousandsx(colValue, formatConfigAss.isFullNumber || false)
  } else if (colType === 'percent') {
    return formatPercentOfCarry(colValue, formatConfigAss.carryNumber, formatConfigAss.fixNumber)
  } else if (colType === 'money') {
    const _countrySymbol = countrySymbol || 'US'
    const _moneySymbol = formatConfigAss.moneySymbol || moneySymbol[_countrySymbol]
    return formatMoneyRound(colValue, _moneySymbol, formatConfigAss.isFullNumber || false)
  } else {
    return colValue || '--'
  }
}

/*
  // textarea 多邮箱 转换为 分割字符串
  emailVal // String textarea文本
  jionKey  // String 分割符
  @return // String 格式化的字符串
*/
export function emailAreaToText(emailVal, jionKey = ',') {
  const trimEmailText = emailVal.trim()
  const emailTrimArray = []
  if (trimEmailText) {
    trimEmailText.split('\n').forEach(item => {
      if (item && item.trim()) {
        emailTrimArray.push(item.trim())
      }
    })
  }
  return emailTrimArray.join(jionKey)
}

export const getRanges = () => {
  const lastWeekEnd = new Date(dayjs().subtract(1, 'weeks').endOf('week').format('YYYY-MM-DD'))
  const today = new Date(dayjs().format('YYYY-MM-DD'))
  return {
    'Last week': [new Date(dayjs().subtract(1, 'weeks').startOf('week').format('YYYY-MM-DD')), lastWeekEnd],
    'Last 4 weeks': [new Date(dayjs().subtract(4, 'weeks').startOf('week').format('YYYY-MM-DD')), lastWeekEnd],
    'Last 13 weeks': [new Date(dayjs().subtract(13, 'weeks').startOf('week').format('YYYY-MM-DD')), lastWeekEnd],
    'Last 26 weeks': [new Date(dayjs().subtract(26, 'weeks').startOf('week').format('YYYY-MM-DD')), lastWeekEnd],
    'Last 52 weeks': [new Date(dayjs().subtract(52, 'weeks').startOf('week').format('YYYY-MM-DD')), lastWeekEnd],
    'Last 104 weeks': [new Date(dayjs().subtract(104, 'weeks').startOf('week').format('YYYY-MM-DD')), lastWeekEnd],
    'Mtd': [new Date(dayjs().startOf('month').format('YYYY-MM-DD')), today],
    'Qtd': [new Date(dayjs().startOf('quarter').format('YYYY-MM-DD')), today],
    'Ytd': [new Date(dayjs().startOf('year').format('YYYY-MM-DD')), today],
    'Lifetime': [new Date(dayjs('2010-01-01').format('YYYY-MM-DD')), today]
  }
}

const pipe = (...fns) => fns.reduce((g, f) => (...args) => f(g(...args)))
const add = (a, b) => a + b
const sum = arr => arr.reduce(add, 0)
const mapKey = (arr, key) => arr.map(item => item[key] ?? 0)
// 获取数组内某个字段和
export const getSum = (arr, key) => {
  return pipe(
    mapKey,
    sum
  )(arr, key)
}

/**
* @description 千位分隔符
*/
export const numFormat = (num, divider = ',') => {
  num = num.toString().split('.') // 分隔小数点
  var arr = num[0].split('').reverse() // 转换成字符数组并且倒序排列
  var res = []
  for (var i = 0, len = arr.length; i < len; i++) {
    if (i % 3 === 0 && i !== 0) {
      res.push(divider)
    }
    res.push(arr[i])
  }
  res.reverse()
  if (num[1]) {
    res = res.join('').concat('.' + num[1])
  } else {
    res = res.join('')
  }
  return res
}

/**
 * 为空判断
 * @returns {boolean}
 */
export function isEmpty() {
  const len = arguments.length
  if (len === 0) {
    return true
  }
  for (let i = 0; i < len; i++) {
    const a = arguments[i]
    if (typeof a === 'undefined' || a == null || (typeof a === 'string' && a.trim() === '')) {
      return true
    } else if (Object.prototype.toString.call(a) === '[object Array]') {
      if (a.length === 0) {
        return true
      }
    } else if (Object.prototype.toString.call(a) === '[object Object]') {
      if (Object.keys(a).length === 0) {
        return true
      }
    }
  }
  return false
}

/**
 * 判断是否选中文本
 * @returns {string}
 */
export const getWindowSelected = () => {
  // debugger
  if (window.getSelection) {
    return window.getSelection().toString()
  } else if (document.getSelection()) {
    return document.getSelection().toString()
  } else {
    const selection = document.selection && document.selection.createRange()
    if (selection.text) {
      return selection.text.toString()
    }
    return ''
  }
}
